//
//  SearchViewController.m
//  Comic
//
//  Created by 程锦 on 16/3/19.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "SearchModel.h"
#import "DetailViewController.h"

#define Data @"http://api.kuaikanmanhua.com/v1/topics/search?keyword=%@&limit=20&offset=0"
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic ,strong)UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *searchTableView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (nonatomic ,copy) NSString *content;
@property (nonatomic ,strong) NSMutableArray *searchArr;
@property (nonatomic ,assign) NSInteger count;
@property (nonatomic ,strong) UIButton *vocie;
@property (nonatomic ,strong) UITextField *searchField;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 隐藏ItemButton
    self.navigationItem.hidesBackButton = YES;
    
    // 创建TableView
    [self createView];
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    // 创建searchBar
    [self searchBarView];
    

}

- (void)viewWillAppear:(BOOL)animated{
    
    [self.navigationController.navigationBar addSubview:_searchBar];
    
    
}

#pragma mark 创建searchBar
- (void)searchBarView{
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 3, self.view.frame.size.width - 64, 38)];
    
    self.searchBar.placeholder = @"搜索作品名、作者名";
    
    self.searchBar.backgroundColor = [UIColor whiteColor];
    
    self.vocie = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_vocie setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
    
    _vocie.frame = CGRectMake(_searchBar.frame.size.width - 25, 12, 20, 20);
    
    [_vocie addTarget:self action:@selector(voice:) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchBar.delegate = self;
    
    self.searchField = [_searchBar valueForKey:@"searchField"];

    if (_searchField) {
        
        // 背景色
        [_searchField setBackgroundColor:[UIColor whiteColor]];
        
        // 设置字体颜色 / 占位符 (必须)
        
        _searchField.textColor = [UIColor grayColor];
        
        [_searchField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
        
    }
    
    [self.navigationController.navigationBar addSubview:_searchBar];
    
    [_searchBar addSubview:_vocie];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    
    [rightButton setFont:[UIFont systemFontOfSize:16]];
    
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    rightButton.frame = CGRectMake(0, 0, 35, 40);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    
    [rightButton addTarget:self action:@selector(rightButton:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark 数据解析
- (void)createData{
    
    NSString *str = [NSString stringWithString: [self.content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:[NSString stringWithFormat:Data,str] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.searchArr = [NSMutableArray array];
        
        NSArray *arr = [responseObject[@"data"]objectForKey:@"topics"];
        
        self.count = arr.count;
        
        if (self.count == 0) {
            
            self.searchTableView.hidden = YES;
            
            self.searchView.hidden = NO;
        }
        
        for (NSDictionary *dic in arr) {
            
            SearchModel *model = [[SearchModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.searchArr addObject:model];
            
        }
        
        [self.searchTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}

#pragma mark 创建TableView
- (void)createView{
    
    UINib *cellNib = [UINib nibWithNibName:NSStringFromClass([SearchTableViewCell class]) bundle:nil];
    
    [self.searchTableView registerNib:cellNib forCellReuseIdentifier:NSStringFromClass([SearchTableViewCell class])];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.searchArr.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SearchModel *model = self.searchArr[indexPath.row];
    
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchTableViewCell class]) forIndexPath:indexPath];
    
    [cell.namePhoto sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
    
    cell.nameTitle.text = model.title;
    
    cell.nameLabel.text = model.user[@"nickname"];
    
        return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SearchModel *model = self.searchArr[indexPath.row];
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    
    detailVC.idNumber = [NSString stringWithFormat:@"%@",model.idNumber];
    
    [self.navigationController pushViewController:detailVC animated:YES];

    
}

#pragma mark searBar时时输入
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    self.content = @"";
    
    if (![searchText isEqualToString:@""]) {
        
        self.content = searchText;
        
        self.searchView.hidden = YES;
        // 数据解析
        [self createData];
    }else{
        
        self.searchView.hidden = NO;
    
    }
    
    
    if (self.content.length != 0) {
        
        [self.vocie removeFromSuperview];
        
    }else if (self.content.length == 0){
        
        [self.searchBar addSubview:self.vocie];
        
    }
}

- (void)voice:(UIButton *)button{
    NSLog(@"wwww");
}

#pragma mark 进入别的页面searBar取消
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    
    [_searchBar removeFromSuperview];
}

#pragma mark 返回
- (void)rightButton:(UIButton *)right{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
